<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <title>React17声明周期</title>
</head>
<body>
<div id="app"></div>
<script src="../lib/17/babel.min.js"></script>
<script src="../lib/17/react.development.js"></script>
<script src="../lib/17/react-dom.development.js"></script>
<script type="text/babel">
  /*
  React 17:
    1. 所有带Will的钩子(除了componentWillUnmount)，都要加UNSAFE_前缀
    2. 新增钩子: getDerivedStateFromProps,  getSnapshotBeforeUpdate.
   */
  class Count extends React.Component {
    constructor(props) {
      super(props);
      console.log('constructor')
    }

    state = {
      count: 0
    }

    add = () => {
      let {count} = this.state;
      this.setState({
        count: ++count
      })
    }

    force = () => {
      this.forceUpdate()
    }

    remove = () => {
      ReactDOM.unmountComponentAtNode(document.querySelector('#app'));
    }

    render() {
      console.log('render');
      return (
        <div>
          <h1>Count:{this.state.count}</h1>
          <button onClick={this.add}>+1</button>
          <button onClick={this.force}>force</button>
          <button onClick={this.remove}>remove</button>
        </div>
      )
    }

    // getDerivedStateFromProps, 在props更改, setState, forceUpdate时调用, 这个用得很少
    static getDerivedStateFromProps(props, state) {
      console.log('getDerivedStateFromProps', props, state)
      // 返回是state，如果state完全取决于props，那么就return props
      // return props
      // 可以对state进行判断后决定是否更新state
      // return state
      return null
    }

    // 组件在页面更新前的快照, 返回值作为snapshotValue参数传递给componentDidUpdate
    getSnapshotBeforeUpdate(prevProps, prevState){
      console.log('getSnapshotBeforeUpdate',prevProps, prevState)
      return 666
    }

    componentDidMount() {
      console.log('componentDidMount')
    }

    componentWillUnmount() {
      console.log('componentWillUnmount')
    }
    // 参数是更新前的props和state
    componentDidUpdate(prevProps,prevState, snapshotValue) {
      console.log('componentDidUpdate',prevProps,prevState,snapshotValue)
    }

    shouldComponentUpdate() {
      console.log('shouldComponentUpdate')
      return true
    }
  }

  ReactDOM.render(<Count name='Sam'/>, document.querySelector('#app'))
</script>
</body>
</html>
